/**
 * 
 */
package net.mikoo.seals.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import org.apache.commons.lang.StringUtils;

/**
 * @author huangxm
 *
 */
public class FileUtil {
	
	public static String getExtName(String fileName){
		
		if(StringUtils.isBlank(fileName)){
			
			return "";
		}
		return fileName.substring(fileName.lastIndexOf(".") + 1);
	}
	
	public static String getFileName(String filePath,String extName){
		String path = filePath+"/"+DateUtil.formate(new Date(), "yyyyMM")+"/"+DateUtil.formate(new Date(), "yyyyMMddHHmmssSSS")+"."+extName;
		return path;
	}
	
	public static String read(String url){
		
		File file = new File(url);
		return read(file);
	}
	
	public static String read(File file){
		
		StringBuffer sb = new StringBuffer();
		BufferedReader reader=null;
		try {
			reader = new BufferedReader(new FileReader(file));
			String configString = null;
			while ((configString = reader.readLine()) != null) {
				sb.append(configString);
	        }
			reader.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
        }
		
		return sb.toString();
	}

	
	public static void readWrite(InputStream stream, String path) {

		OutputStream bos = null;
		try {
			bos = new FileOutputStream(path);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		int bytesRead = 0;
		byte[] buffer = new byte[8192];

		try {
			while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
				bos.write(buffer, 0, bytesRead);
			}
			bos.flush();
		} catch (IOException e) {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}
	
	public static byte[] toByteArray(InputStream input) throws IOException {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		byte[] buffer = new byte[4096];
		int n = 0;
		while (-1 != (n = input.read(buffer))) {
			output.write(buffer, 0, n);
		}
		return output.toByteArray();
	}
}
